package com.reebake.ideal.security.properties;

import cn.hutool.core.util.ObjUtil;
import com.reebake.ideal.security.constants.AuthenticationFactoryType;
import com.reebake.ideal.security.core.AuthenticationFactorConvertor;
import com.reebake.ideal.security.handler.CodeAuthenticationFactorConvertor;
import com.reebake.ideal.security.handler.QrcodeAuthenticationFactorConvertor;
import com.reebake.ideal.security.handler.UsernameAuthenticationFactorConvertor;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.reebake.ideal.security.core.SecurityConstants.PROPERTY_PREFIX;

@Data
@ConfigurationProperties(prefix = PROPERTY_PREFIX)
public class ServerSecurityProperties implements InitializingBean {
    private Long accessTokenExpireIn = 24 * 60 * 60 * 1000L;

    private String formLoginUrl = "/auth/login";

    private String formLogoutUrl = "/auth/logout";

    private String tokenRefreshUrl = "/auth/refresh";

    private Map<String, Class<?>> authenticationFactorConvertors = new HashMap<>();

    /**
     * 最大登录次数，否则账户被锁
     */
    private Integer maxLoginTryTimes = 0;
    /**
     * 触发防机器人验证码次数, 0表示忽略
     */
    private Integer maxCaptchaTriggerTimes = 0;
    /** 启用双因子认证，默认关闭 */
    private Boolean enable2FA = false;

    public Date getAccessTokenExpireAt() {
        return new Date(System.currentTimeMillis() + this.getAccessTokenExpireIn());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(ObjUtil.isNull(authenticationFactorConvertors.get(AuthenticationFactoryType.USERNAME))) {
            authenticationFactorConvertors.put(AuthenticationFactoryType.USERNAME, UsernameAuthenticationFactorConvertor.class);
        }
        if(ObjUtil.isNull(authenticationFactorConvertors.get(AuthenticationFactoryType.CODE))) {
            authenticationFactorConvertors.put(AuthenticationFactoryType.CODE, CodeAuthenticationFactorConvertor.class);
        }
        if(ObjUtil.isNull(authenticationFactorConvertors.get(AuthenticationFactoryType.QR_CODE))) {
            authenticationFactorConvertors.put(AuthenticationFactoryType.QR_CODE, QrcodeAuthenticationFactorConvertor.class);
        }
    }
}
